package com.earthea.chatbot.login.controller;

import cn.hutool.core.util.IdUtil;
import com.earthea.cache.CacheService;
import com.earthea.common.util.Base64;
import com.earthea.chatbot.common.entity.BaseRsp;
import com.earthea.chatbot.login.common.constant.Constants;
import com.earthea.chatbot.login.entity.response.CaptchaRsp;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码操作处理
 */
@RestController
@RequestMapping("/api")
public class CaptchaController {

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Value("${app.captcha.enabled:true}")
    private boolean captchaEnabled;

    @Autowired
    private CacheService cacheService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public BaseRsp getCode() {
        CaptchaRsp response = BaseRsp.success(CaptchaRsp.class);
        response.setCaptchaEnabled(captchaEnabled);
        if (!captchaEnabled) {
            return response;
        }

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODES_CACHE_NAME + uuid;

        String capStr = null;
        String code = null;
        BufferedImage image = null;

        // 生成验证码
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);

        cacheService.setex(verifyKey, code, 120);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return BaseRsp.failed(e.getMessage(), CaptchaRsp.class);
        }
        response.setUuid(uuid);
        response.setImg(Base64.encode(os.toByteArray()));
        return response;
    }
}
